package com.btpj.jetpack.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import org.koin.androidx.viewmodel.ext.android.getViewModel
import kotlin.reflect.KClass

/**
 * 注入ViewModel和DataBinding的Fragment基类
 *
 * @author LTP 2020/7/7
 */
abstract class BaseFragment<VM : BaseViewModel, B : ViewDataBinding> : Fragment() {

    lateinit var mViewModel: VM
    lateinit var mBinding: B

    /** Fragment的布局ID */
    abstract fun getLayoutId(): Int

    /** View初始化相关 */
    abstract fun initView()

    /** 重写实现LiveData监听逻辑 */
    open fun createObserve() {}

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViewModel()
        initDataBinding()
        initView()
    }

    /**
     * 初始化ViewModel相关
     */
    private fun initViewModel() {
        mViewModel =
            getViewModel(this.javaClass.kotlin.supertypes[0].arguments[0].type!!.classifier!! as KClass<VM>)
        createObserve()
        mViewModel.start()
    }

    /**
     * 初始化DataBinding相关
     */
    private fun initDataBinding() {
        // dataBinding绑定lifecycle
        mBinding.lifecycleOwner = this
    }
}